package com.food.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;


import com.food.ucenter.mapper.UsersMapper;
import com.food.ucenter.model.dto.AuthParamsDto;
import com.food.ucenter.model.dto.UserExt;
import com.food.ucenter.model.po.Users;

import com.food.ucenter.service.AuthService;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author Mr.M
 * @version 1.0
 * @description 账号名密码方式
 * @date 2023/2/24 11:56
 */
@Service("password_authservice")
public class PasswordAuthServiceImpl implements AuthService {

 @Autowired
 UsersMapper usersMapper;

 @Autowired
 PasswordEncoder passwordEncoder;

 @Override
 public UserExt execute(AuthParamsDto authParamsDto) {
  //账号
  String openid=authParamsDto.getOpenid();
  //账号是否存在
  //根据username账号查询数据库
  Users users = usersMapper.selectOne(new LambdaQueryWrapper<Users>().eq(Users::getOpenid, openid));
  //查询到用户不存在，要返回null即可，spring security框架抛出异常用户不存在
  if(users==null){
   throw new RuntimeException("账号不存在");
  }
  //验证密码是否正确
  //如果查到了用户拿到正确的密码
  String passwordDb = users.getUserPassword();
  //拿 到用户输入的密码
  String passwordForm = authParamsDto.getPassword();
  //校验密码
  boolean matches = passwordEncoder.matches(passwordForm, passwordDb);
  if(!matches){
   throw new RuntimeException("账号或密码错误");
  }
  UserExt userExt = new UserExt();
  BeanUtils.copyProperties(users,userExt);

  return userExt;
 }
}
